
package com.changhongit.order.logger;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * Created by sjl on 2019/7/29.
 */


@Aspect
@Component
public class LogIntercept {
	private static final Logger logger = LoggerFactory.getLogger(LogIntercept.class);

	@Around(value = "execution(* com.changhongit.order.controller..*.*(..)) && @annotation(systemLogger)")
	public Object around(ProceedingJoinPoint joinPoint, SystemLogger systemLogger) {
		StringBuffer sb = new StringBuffer();
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		String methodName = method.getName();
		if (StringUtils.isEmpty(systemLogger.desc()))
			logger.info(systemLogger.desc());
		String aroundStartLog = "----------------------- Method " + methodName + " execute begin -----------------------";
		if (!StringUtils.isEmpty(systemLogger.aroundStartLog()))
			aroundStartLog = systemLogger.aroundStartLog();
		logger.info(aroundStartLog);
		if (!StringUtils.isEmpty(systemLogger.operation()))
			logger.info(systemLogger.operation());
		Object[] objs = joinPoint.getArgs();
		for (Object o : objs) {
			sb.append(o + ";");
		}
		logger.info(" 传入参数 : " + sb.toString());
		long startTime = System.currentTimeMillis();
		Object object = null;
		try {
			object = joinPoint.proceed();
//			if(object != null){
//				int size = object.toString().length();
//				if(size<102400){
//					logger.info("返回信息:" + object.toString());
//				}else {
//					logger.info("返回信息:调用完成，数据大小：{} KB",size/1024 );
//				}
//
//			}else {
//				logger.info("返回信息: null");
//			}
//
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		String aroundEndLog = "----------------------- Method " + methodName + " execute end   -----------------------";
		if (!StringUtils.isEmpty(systemLogger.aroundEndLog()))
			aroundEndLog = systemLogger.aroundEndLog();
		logger.info(aroundEndLog);

		if (systemLogger.recodecConsumedTime())
			logger.info("Method " + methodName + " is consumed " + (endTime - startTime) + " milliseconds .");

		return object;
	}
}
